# -*- encoding:utf-8 -*-
# @Time : 2025/3/16 10:51
# @Author : xunter
# @Email : 3133739348@qq.com
# @File : serializers.py
# @Software : PyCharm
from rest_framework import serializers
from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer

from community.models import Label, Article, Comment


class LabelSerializer(ModelSerializer):
    class Meta:
        model = Label
        fields = '__all__'

class ArticleSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.username', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    label_name = serializers.CharField(source='label.name', read_only=True)
    class Meta:
        model = Article
        exclude = ['is_delete']

        extra_kwargs = {
            'page_view':{'read_only':True},
            'priority':{'read_only':True},
        }

class CommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.username', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    son_comment_count = SerializerMethodField()
    # son_comment_count值会调用函数 get_son_comment_count(get_属性名)的函数来得到，把函数的返回值作为属性值
    def get_son_comment_count(self, comment):
        """
        返回子评论的条数
        :param comment:
        :return:
        """
        return comment.parent_comment_set.count()

    class Meta:
        model = Comment
        exclude = ['is_delete']

class SonCommentSerializer(ModelSerializer):
    article_name = serializers.CharField(source='article.title', read_only=True)
    user_name = serializers.CharField(source='user.username', read_only=True)
    reply_username = serializers.CharField(source='reply_comment_set.user.username', read_only=True)
    class Meta:
        model = Comment
        exclude = ['is_delete']